package com.i2works.smartluolong.manageapi.utils;

import com.alibaba.fastjson.JSONObject;
import com.i2works.smartluolong.manage.entity.admin.AdminUserDO;
import com.i2works.smartluolong.manage.entity.admin.AdminUserQuery;
import com.i2works.smartluolong.manage.service.admin.IAdminUserService;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.base.ShiroConstants;
import com.i2works.smartluolong.utils.common.SmsUtil;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.utils.redis.RedisSessionDAO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户登陆信息存储
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2016/1/17 14:57
 */
@Component
public class BaseModule {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private RedisSessionDAO redisSessionDAO;


    /**
     * 获取登陆用户
     */
    protected AdminUserDO getLoginUser() {
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if (principal != null) {
            JSONObject userObject = (JSONObject) principal;
            AdminUserDO user = new AdminUserDO();
            user.setId(userObject.getInteger(ShiroConstants.APP_USERID));
            user.setUserName(userObject.getString(ShiroConstants.APP_USERNAME));
            return user;
        } else {
            return null;
        }
    }

    /**
     * 获取登陆用户ID
     */
    protected Integer getUserId() {
        return getLoginUser().getId();
    }

    /**
     * 获取登陆账号
     */
    protected String getUserName() {
        return getLoginUser().getUserName();
    }


    /**
     * 获取用户名
     */
    protected String getUserName(Integer userId) {
        return getUser(userId).getUserName();
    }


    /**
     * 判断短信验证码
     *
     * @param phone 手机号
     * @param code  验证码
     */
    protected Result checkSmsCode(String phone, String code) {
        if (StringUtils.isBlank(code)) {
            return R.error(MsgEnum.SMS_CODE_EMPTY.getMsg());
        } else {
            //判断验证码是否正确
            Result contrast = smsUtil.contrast(phone, code);
            //对比失败返回
            if (!contrast.getSuccess()) {
                return contrast;
            } else {
                //删除缓存
                smsUtil.delete(phone);
            }
            return R.success();
        }
    }

    /**
     * 判断用户是否存在
     *
     * @param value 参数
     * @param type  类型（1用户名，2编号）
     * @return 存在返回true，不存在返回false
     */
    public Boolean existUser(Object value, Integer type) {
        if (value == null) {
            return false;
        }
        //判断账号是否存在
        AdminUserQuery userQuery = new AdminUserQuery();
        switch (type) {
            case 1:
                userQuery.setUserName(String.valueOf(value));
                break;
            case 2:
                userQuery.setId(Integer.parseInt(value.toString()));
                break;
            default:
                userQuery.setUserName(String.valueOf(value));
                break;
        }
        try {
            int queryCount = adminUserService.queryCount(userQuery);
            //大于0，查到数据，返回true，否则没有数据，返回false
            return queryCount > 0;
        } catch (ServiceException e) {
            logger.error("查询用户异常：" + e.getMessage());
            return false;
        }
    }

    //根据用户id获取用户对象
    public AdminUserDO getUser(Integer userId) {
        AdminUserQuery userQuery = new AdminUserQuery();
        userQuery.setId(userId);
        AdminUserDO user = null;
        try {
            user = adminUserService.query(userQuery);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return user;
    }





}
